<!-- tinymc富文本 -->

<template>
  <div>
    <editor v-model="myValue" :setting="{ inline: false }" :init="init" :disabled="disabled" @onClick="onClick">
    </editor>
    <dialog id="myDialog">
      <el-progress :text-inside="true" :stroke-width="24" :percentage="percentage" status="success"></el-progress>
    </dialog>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce.min.js'
import editor from '@tinymce/tinymce-vue'
import '../assets/langs/zh_CN.js'
import 'tinymce/themes/silver/theme.min.js'
import 'tinymce/skins/ui/oxide/skin.min.css'
import 'tinymce/skins/content/default/content.css'
import 'tinymce/plugins/image/plugin'
import 'tinymce/plugins/imagetools/plugin'
import 'tinymce/plugins/media/plugin'
import 'tinymce/plugins/table'
import 'tinymce/plugins/pagebreak'
import 'tinymce/plugins/lists/plugin'
import 'tinymce/plugins/wordcount/plugin'
import "tinymce/icons/default" // 图标 -解决测试环境找不icon问题

import axios from 'axios'
export default {
  components: {
    editor
  },
  props: {
    //传入一个value，使组件支持v-model绑定
    value: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    plugins: {
      type: [String, Array],
      default:
        // 'colorpicker colorpicker contextmenu image imagetools lists table textcolor wordcount'
        'colorpicker colorpicker contextmenu image media imagetools lists table textcolor wordcount pagebreak styleselect fontselect fontsizeselect'
    },
    toolbar: {
      type: [String, Array],
      default:
        // 'undo redo | | bold  italic | underline | strikethrough | alignleft  aligncenter alignright | outdent indent  blockquote  removeformat subscript superscript bullist numlist image charmap  table  forecolor backcolor '
        () => ['undo redo | | bold  italic | underline | strikethrough | alignleft  aligncenter alignright outdent indent  blockquote  removeformat subscript superscript bullist numlist | image media charmap table forecolor backcolor styleselect',
          'fontselect fontsizeselect | customlayout pagebreak']
    }
  },
  data () {
    return {
      //初始化配置
      init: {
        language_url: '../assets/langs/zh_CN.js', // 这里需要单独处理
        language: 'zh_CN',
        skin_url: 'tinymce/skins/ui/oxide/skin.min.css', // skin路径
        content_css: 'tinymce/skins/content/default/content.min.css',
        convert_urls: false,
        height: 500,
        plugins: this.plugins,
        toolbar: this.toolbar,
        setup: this.setup,
        branding: false,
        menubar: true,
        forced_root_block: "p",
        force_br_newlines: false,
        force_p_newlines: true,
        force_div_newlines: false,
        force_span_newlines: false,
        content_style: 'body {font-size: 14pt; font-family:Arial;text-indent: 0em;}',
        //一键排版
        layout_options: {
          style: {
            'text-align': 'justify',
            'text-indent': '0em',
            'line-height': 2,
            'font-family': 'Arial',
            'font-size': '12px'
          },
          filterTags: ['table>*', 'tbody'], //'table，'tbody','td','tr' 将会忽略掉 同时 table>*，忽略table 标签 以及所有子标签
          //clearStyle: ['font-size'],//text-indent 将会被清除掉
          tagsStyle: {
            'p': {
              'font-size': '12px'
            },
            'span': {
              'font-size': '12px'
            }
            // 'table': {
            //   'line-height': 2,
            //   'text-align': 'center'
            // },
            // 'table,tbody,tr,td': { //支持并集选择
            //   'line-height': 2
            // },
            // 'tr>td,table>tbody': { //支持, 精准定位 通过 ' > '
            //   'line-height': 2,
            //   'text-align': 'center'
            // }
          }
        },
        images_upload_handler: (blobInfo, success, failure) => {
          var formData;
          formData = new FormData();
          var file = blobInfo.blob(); //转化为易于理解的file对象
          formData.append('file', file);
          let that = this
          document.getElementById('myDialog').showModal()
          that.percentage = 0
          let uploadUrl = process.env.VUE_APP_BASE_API + `/upload/file`
          //const { url } = that.uploadImg(formData)
          axios.post(uploadUrl, formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            onUploadProgress (e) {
              const complete = e.loaded / e.total * 100
              that.percentage = Math.round(complete)
            }
          }).then(response => {
            const data = response.data.data.url;
            document.getElementById('myDialog').close()
            success(data)
          }).catch(error => {
            console.log(error);
            this.$message.error("上传失败:" + error);
          })

        },
        // img_template_callback: data => {
        //   return `<img width="700" height="394" controls="controls" src=${data.source} />`
        // },
        file_picker_types: 'media',
        file_picker_callback: (callback, value, meta) => {
          if (meta.filetype === 'media') {
            const input = document.createElement('input')
            input.setAttribute('type', 'file')
            const that = this // 为 Vue 构造函数中的 this，指向 Vue 实例对象
            input.onchange = async function () {
              const file = this.files[0] // 为 HTMLInputElement 构造函数中的 this，指向 input 实例对象
              const { url } = await that.uploadFile(file)
              document.getElementById('myDialog').close()
              callback(url)
            }
            input.click()
          }
          cb(img_url, { alt: img_title, width: '100%', height: 'auto' });
        },
        video_template_callback: data => {
          return `<video width="700" height="394" controls="controls" src=${data.source} />`
        },
        resize: false,
      },
      myValue: '',
      percentage: 0
    }
  },
  mounted () {
    this.myValue = this.value || ''
    tinymce.init({})
  },
  methods: {
    onClick (e) {
      this.$emit('onClick', e, tinymce)
    },
    clear () {
      this.myValue = ''
    },
    setup: function (editor) {
      let that = this
      editor.ui.registry.addButton('customlayout', {
        text: '排版',
        onAction: function () {
          console.log(111111)
          // 获取编辑器内容  
          var content = editor.getContent();
          console.log(content)
          var div = document.createElement('div')
          div.innerHTML = content
          var divElements = div.querySelectorAll('div');
          for (var i = 0; i < divElements.length; i++) {
            var divElement = divElements[i];
            divElement.style.fontSize = '12pt'
            divElement.style.fontFamily = 'Arial'
          }
          // 在编辑器内容中插入自定义布局
          //var newContent = '<div style="text-indent: 0em; font-size:14pt font-family: Arial; line-height: 2; color: #000;">' + content + '</div>';

          // 将修改后的内容设置回编辑器
          //

          var pElements = div.querySelectorAll('p');
          for (var i = 0; i < pElements.length; i++) {
            var pElement = pElements[i];
            pElement.style.fontSize = '12pt'
            pElement.style.fontFamily = 'Arial'
            pElement.style.textIndent = '0em'
            pElement.style.lineHeight = 2
            pElement.style.maxWidth = '100%'
            pElement.style.height = 'auto'
          }

          var spanElements = div.querySelectorAll('span');
          for (var i = 0; i < spanElements.length; i++) {
            var spanElement = spanElements[i];
            spanElement.style.fontSize = '12pt'
            spanElement.style.fontFamily = 'Arial'
            if (spanElement.parentNode.tagName === 'DIV') {
              let p = document.createElement('p')
              p.innerHTML = spanElement.innerHTML
              spanElement.parentNode.replaceChild(p, spanElement)
            }
          }
          // 获取所有的图片、视频和音频元素
          var mediaElements = div.querySelectorAll('img, video');

          //遍历所有的图片、视频和音频元素，设置它们的样式
          for (var i = 0; i < mediaElements.length; i++) {
            var mediaElement = mediaElements[i];
            console.log(mediaElement.className)
            if (mediaElement.className != 'mce-pagebreak') {
              // 设置元素的宽度和高度
              mediaElement.style.width = '700px';
              mediaElement.style.maxWidth = '100%';
              //mediaElement.style.height = 'auto';
              mediaElement.style.display = 'block';
              mediaElement.style.margin = 'auto';
              // 设置元素的居中样式
              // mediaElement.parentElement.style.display = 'flex';
              // mediaElement.parentElement.style.justifyContent = 'center';
              mediaElement.parentElement.style.textIndent = 0
              mediaElement.parentElement.style.display = 'block';
              mediaElement.parentElement.style.margin = 'auto';
            }
          }
          var audioElements = div.querySelectorAll('audio');
          for (var i = 0; i < audioElements.length; i++) {
            var audioElement = audioElements[i];
            // 设置元素的居中样式 layoutFV
            audioElement.parentElement.style.textAlign = 'center'
            audioElement.parentElement.style.textIndent = 0
            // audioElement.parentElement.style.display = 'block';
            // audioElement.parentElement.style.padding = 'auto';
          }

          console.log(div)
          //debugger
          editor.setContent(div.innerHTML);
          that.$emit('input', div.innerHTML)
        }
      });
      editor.ui.registry.addButton('pagebreak', {
        text: '分页',
        onAction: function () {
          editor.insertContent('<class="pagebreak" />');
        }
      });
    },
    async uploadFile (file, folder = 'images') {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('folder', folder)
      document.getElementById('myDialog').showModal()
      let that = this
      that.percentage = 0
      // 注：此为调用后端上传接口，需根据实际情况进行调整
      const { data } = await axios({
        method: 'POST',
        url: process.env.VUE_APP_BASE_API + `/upload/file`,
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress (e) {
          const complete = e.loaded / e.total * 100
          that.percentage = Math.round(complete)
        }
      })

      return {
        url: data.data.url,
        //name: data.data.poster
      }
    },
    async uploadImg (file, folder = 'images') {
      // const formData = new FormData()
      // formData.append('file', file)
      // formData.append('folder', folder)

      // 注：此为调用后端上传接口，需根据实际情况进行调整
      const { data } = await axios({
        method: 'POST',
        url: process.env.VUE_APP_BASE_API + `/upload/file`,
        data: file,
        headers: { 'Content-Type': 'multipart/form-data' }
      })

      return {
        url: data.data.url
      }
    }
  },
  watch: {
    value (newValue) {
      this.myValue = newValue
    },
    myValue (newValue) {
      this.$emit('input', newValue)
    }
  }
}
</script>

<style scoped>
#myDialog {
  width: 800px;
}
</style>

<style>
/* 在el-dialog中tinymce z-index 被太小而被遮挡时要加这两句 */
.tox-tinymce-aux {
  z-index: 99999 !important;
}

.tinymce.ui.FloatPanel {
  z-Index: 99;
}
</style>
